<template>
  <el-upload class="du-container" :class="{'du-border': !localImage}" :action="action" :show-file-list="false" accept="image/jpeg,image/jpg,image/png" :on-success="handleUploadSuccess">
    <img v-if="localImage" :src="localImage" class="du-image">
    <div v-else class="du-info">
      <i class="el-icon-plus"></i>
    </div>
  </el-upload>
</template>

<script>
const { origin } = window.location
const baseURL = `${origin}/api/`
export default {
  // 全局感知
  name: "SettingUpload",

  // 模板依赖
  components: {},
  filters: {},

  // 接口
  props: {
    image: {
      type: String,
      required: false,
      default: ''
    }
  },

  // 本地状态
  data () {
    return {
      action: `${baseURL}upload_admin`,
      localImage: this.image
    };
  },
  computed: {},

  // 事件
  watch: {
    image (image) {
      this.localImage = image
    },
    localImage (localImage) {
      this.$emit('update:image', localImage)
    }
  },
  beforeCreate () { },
  created () { },
  beforeMount () { },
  mounted () { },
  beforeUpdate () { },
  updated () { },
  beforeDestroy () { },
  destroyed () { },

  // 非响应式的属性
  methods: {
    handleUploadSuccess (response) {
      const { data: { url } } = response
      this.localImage = url
    }
  }
}
</script>

<style lang="less" scoped>
.du {
  &-container {
    position: relative;
    display: inline-block;
    box-sizing: border-box;
    width: 160px;
    height: 120px;

    background: #f8f8f8;
  }
  &-border {
    border: 1px dashed #979797;
  }
  &-image {
    overflow: hidden;

    box-sizing: border-box;
    width: 160px;
    height: 120px;
  }
  &-info {
    position: absolute;
    top: 50%;
    left: 50%;

    transform: translate(-50%, -50%);

    color: #d8d8d8;

    font-size: 36px;
  }
}
</style>